package com.dongnao.proxyframework.net.okhttp;

import android.util.Log;

import com.dongnao.proxyframework.net.HttpRequest;
import com.dongnao.proxyframework.net.ICallback;

import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2018/4/23.
 */

public class OkHttpRequest implements HttpRequest {

    private static final String TAG = "Jiang";
    private OkHttpClient okHttpClient;

    public OkHttpRequest() {
        okHttpClient = new OkHttpClient();
    }


    @Override
    public void get(String url, Map<String, String> params, final ICallback callback) {
        StringBuffer sb = new StringBuffer("?");
        //拼接 get请求 url
        if (null != params) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                sb.append(entry.getKey());
                sb.append("=");
                sb.append(entry.getValue());
                sb.append("&");
            }
        }
        sb.deleteCharAt(sb.length() - 1);
        url += sb.toString();

        final Request request = new Request.Builder().get().url(url).build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.onFailure(404, e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                Log.d(TAG, response.body().string());
                callback.onSuccess(response.body().string());
            }
        });

    }

    @Override
    public void post(String url, Map<String, String> params, ICallback callback) {

    }
}
